package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //我要拿到所有的请求的数据
        //将数据封装到map集合中
        Map<String, String[]> map = request.getParameterMap();
        //创建一个user对象
        User user = new User();

        //将数据封装到user对象中
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        //通过业务类对象调用添加用户的方法
        int result = new UserService().addUser(user);

        PrintWriter pw = response.getWriter();
        //判断结果
        if (result == 1) {
            response.sendRedirect("/add_ok.jsp");
        } else if (result == 0) {
            pw.print("<h2>用户添加数据错误!请重新输入!</h2>");
            response.setHeader("refresh", "1;url=http://localhost:8080/add.jsp");
        } else if (result == 2) {
            pw.print("<h2>用户已存在! 请重新录入数据!</h2>");
            response.setHeader("refresh", "1;url=http://localhost:8080/add.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
